package org.spider.core.executor.shape;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.context.SpiderContext;
import org.spider.api.domain.utilDomain.KeyValue;
import org.spider.api.domain.utilDomain.SpiderNode;
import org.spider.api.executor.ShapeExecutor;
import org.spider.core.utils.ExpressionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 定义变量执行器
 *
 * @author Administrator
 */
@Component
public class VariableExecutor implements ShapeExecutor {
    private static final String VARIABLE = "variable";
    private static final Logger logger = LoggerFactory.getLogger(VariableExecutor.class);

@Override
public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
    logger.debug(this.getClass().getName() + "执行了");
    // variable列表必须按照前端的顺序来传递，因为变量之间可能存在依赖关系，例如B的变量定义依赖A，那么必须先计算A。
    List<KeyValue> variableList = node.getDictListByKey(VARIABLE);
    if (variableList == null || variableList.isEmpty()) {
        logger.error("变量列表为空,如果不需要设置值，请删掉该节点，否则请至少配置一组变量");
        return;
    }
    for (KeyValue kv : variableList) {
        Object value = null;
        String variableName = kv.getKey();
        String variableValue = kv.getValue();
        try {
            value = ExpressionUtils.execute(variableValue, variables);
            String valueStr = value != null ? value.toString().replace("\n", " ") : null;
            logger.info("设置变量{}={}", variableName, valueStr);
        } catch (Exception e) {
            logger.error("设置变量{}出错,异常信息:{}", variableName, e);
            ExceptionUtils.wrapAndThrow(e);
        }
        variables.put(variableName, value);
    }
}

    @Override
    public String supportShape() {
        return "variable";
    }

    @Override
    public boolean isThread() {
        return false;
    }

}
